package com.lihepeng.leecode.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
// 资源类
class MyCache{
    private volatile Map<String,Object> cache= new HashMap<>();
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    public void setMap(String key,String val) {
        try {
            Thread.sleep(300);
        }catch (Exception e) {
            e.printStackTrace();
        }
        ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t 正在写入"+key);
            this.cache.put(key,val);
            System.out.println(Thread.currentThread().getName()+"\t 写入完成");
        }finally {
            writeLock.unlock();
        }
    }
    public void getMap(String key) {
        ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t 正在读取"+key);
            Object o = this.cache.get(key);
            System.out.println(Thread.currentThread().getName()+"\t 读取完成"+o);
        }finally {
            readLock.unlock();
        }

    }
}
public class ReadWriteLockDemo {
    public static void main(String[] args) throws InterruptedException {
        MyCache myCache = new MyCache();
        // 模拟5个线程来写
        for (int i=0;i<5;i++) {
            final int inttemp = i;
            new Thread(()->{
                myCache.setMap(inttemp+"",inttemp+"");
            },"t"+i).start();
        }
        Thread.sleep(1000);
        // 模拟5个线程来读
        for (int i=0;i<5;i++) {
            final int inttemp = i;
            new Thread(()->{
                myCache.getMap(inttemp+"");
            },"r"+i).start();
        }
    }
}
